package org.lookahead.parent.common.utils;

import cn.hutool.core.util.StrUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.google.common.base.Splitter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;


@Slf4j
public class DingTalkUtil {

    static String WEBHOOK = "https://oapi.dingtalk.com/robot/send?timestamp={}&sign={}";

    /**
     * 发送钉钉消息
     *
     * @param access_token 自定义机器人的access_token
     * @param secret       机器人的密钥
     * @param mobiles      群里@的手机号列表
     * @param content      消息内容
     * @return boolean
     */
    public static Boolean sendMessage(String access_token, String secret, List<String> mobiles, String content) {
        try {
            Long timestamp = System.currentTimeMillis();
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            String url = StrUtil.format(WEBHOOK, timestamp, sign);
            log.info("发送钉钉消息:钉钉群token:{},手机列表:{},内容:{}", access_token, mobiles, content);
            // sign字段和timestamp字段必须拼接到请求URL上，否则会出现 310000 的错误信息
            DingTalkClient client = new DefaultDingTalkClient(url);
            OapiRobotSendRequest req = new OapiRobotSendRequest();
            // 定义文本内容
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent(content);
            // 定义 @ 对象
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            at.setAtMobiles(mobiles);
            // 设置消息类型
            req.setMsgtype("text");
            req.setText(text);
            req.setAt(at);
            OapiRobotSendResponse rsp = client.execute(req, access_token);
            log.info("发送钉钉消息返回结果：{},{}", rsp.getCode(), rsp.getBody());
        } catch (Exception e) {
            log.error("发送钉钉消息失败", e);
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String secret = "SEC7bca165dff481a099891c5f9055358112863c4407522e44bce5cc3be0579df98";
        String access_token = "b2aafb5614256ceaf35c72e143648c3e73de09283b38b2c3ad7794a24f87c004";
        List<String> mobiles = Splitter.on(",").splitToList("18601377252,18217289787,13522376411,18813119881");
        Boolean result = sendMessage(access_token, secret, mobiles, "老师您好，您合作的学校：[学校名1，学校名2]部分教材即将到期，请及时查看并与学校沟通");
        System.out.println(result);
    }
}
